package com.djinfo.work.service.impl;

import com.djinfo.work.common.bean.AjaxJson;
import com.djinfo.work.common.service.impl.BaseServiceImpl;
import com.djinfo.work.common.util.StringUtil;
import com.djinfo.work.dao.*;
import com.djinfo.work.dao.impl.MessagesDaoImpl;
import com.djinfo.work.entity.*;
import com.djinfo.work.service.AttachmentService;
import com.djinfo.work.service.MessagesService;
import com.djinfo.work.service.MessagesUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 *
 */
@Service("MessagesService")
public class MessagesServiceImpl extends BaseServiceImpl<SysMessageEntity,MessagesDaoImpl> implements MessagesService {

	@Autowired
	private MessagesDao messagesDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private DictionariesDao dictionariesDao;

	@Autowired
	private AttachmentService attachmentService;

	@Autowired
	private MessagesUsersService messagesUsersService;

	@Autowired
	private DepartmentDao departmentDao;

	@Autowired
	private RoleUserDao roleUserDao;

	@Autowired
	private RoleDao roleDao;


	@Override
	public SysMessageEntity getMessagesById(String id) {
		return messagesDao.getMessagesById(id);
	}

	@Override
	public List<SysMessageEntity> page(SysMessageEntity sysMessageEntity, Integer pageNum, Integer pageSize) {
		return messagesDao.page(sysMessageEntity,  pageNum,  pageSize);
	}

	@Override
	public List<SysMessageEntity> list() {
		return messagesDao.list();
	}

	@Override
	public Integer getAllRowCount() {
		return messagesDao.getAllRowCount();
	}

	@Override
	public Integer getCountBy(SysMessageEntity sysMessageEntity) {
		return messagesDao.getCountBy(sysMessageEntity);
	}

	/**
	 * 初始化数据，获取消息类型，各部门成员，登录人消息
	 * @param session
     * @return
     */
	@Override
	public AjaxJson getInitInfo(HttpSession session) {
		AjaxJson ajaxJson = new AjaxJson();
		HashMap<String, Object> map = new HashMap<>();
		String userid =(String) session.getAttribute("userId");
		TbSysUsers tbSysUsers = userDao.get(userid);
		String type = "informationType";
		List<Dictionaries> dictionariesList = dictionariesDao.messagesTypeList(type);
		List<Department> departmentList1 = departmentDao.getOneDepartid();
		for(int i=0;i<departmentList1.size();i++){
			List<Department> departmentList = departmentDao.setTwoToOne(departmentList1.get(i).getId());
			int length = departmentList.size();
			for(int j=0;j<length;j++){
				ArrayList<TbSysUsers> tbSysUsersArrayList =new ArrayList<>();
				String id=departmentList.get(j).getId();
				tbSysUsersArrayList =userDao.getUsers(id);
				departmentList.get(j).setDicUsersList(tbSysUsersArrayList);
			}
			departmentList1.get(i).setDepartmentList(departmentList);
		}
		if(StringUtil.isNotEmpty(departmentList1)){
		}else{
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
		}
		map.put("username", tbSysUsers.getUserName());
		map.put("dictionariesList",dictionariesList);
		map.put("list",departmentList1);
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	/**
	 * 获取消息类型和消息状态
	 * @param session
     * @return
     */
	@Override
	public AjaxJson getmessagesInfo(HttpSession session) {
		AjaxJson ajaxJson = new AjaxJson();
		HashMap<String, Object> map = new HashMap<>();
		try{
			String type = "informationType";
			String status = "informationStatus";
			List<Dictionaries> dictionariesList = dictionariesDao.messagesTypeList(type);
			List<Dictionaries> dictionariesList1 = dictionariesDao.messagesStatusList(status);
			map.put("typeList",dictionariesList);
			map.put("statusList",dictionariesList1);
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	/**
	 * 消息列表
	 * @param sysMessageEntity
	 * @param pagenum
	 * @param pagesize
     * @return
     */
	@Override
	public AjaxJson list(SysMessageEntity sysMessageEntity, Integer pagenum, Integer pagesize,String userID) {
		HashMap<String, Object> map = new HashMap<>();
		AjaxJson ajaxJson = new AjaxJson();
		try {
			String roleName = getRoleName(userID);
			List<SysMessageEntity> res = new ArrayList<>();
			Integer count=0;
			if(roleName.indexOf("admin")!=-1){
				res = messagesDao.page(sysMessageEntity,pagenum,pagesize);
				for (int i = 0; i < res.size(); i++) {
					String userId = res.get(i).getReceiveObject();
					String[] userIdArr = userId.split(",");
					String userName= "";
					for (int j = 0; j < userIdArr.length; j++) {
						TbSysUsers users = userDao.get(userIdArr[j]);
						if(null!= users){
							userName +=users.getUserName()+",";
						}
					}
					res.get(i).setReceiveName(userName);
				}

				if(StringUtil.isNotEmpty(sysMessageEntity.getTitle())||StringUtil.isNotEmpty(sysMessageEntity.getType())||StringUtil.isNotEmpty(sysMessageEntity.getStatus())){
					count = messagesDao.getCountBy(sysMessageEntity);
				}else{
					count = messagesDao.getAllRowCount();
				}


			}else{
				sysMessageEntity.setReceiveObject(userID);
				sysMessageEntity.setPublish(userDao.get(userID).getUserName());
				res = messagesDao.myPage(sysMessageEntity,pagenum,pagesize);
				TbSysUsers users = userDao.get(userID);
				for (int i = 0; i < res.size(); i++) {
					res.get(i).setReceiveName(users.getUserName());
				}
				if(StringUtil.isNotEmpty(sysMessageEntity.getTitle())||StringUtil.isNotEmpty(sysMessageEntity.getType())||
						StringUtil.isNotEmpty(sysMessageEntity.getStatus())||StringUtil.isNotEmpty(sysMessageEntity.getReceiveObject())
						){
					count = messagesDao.getMyCount(sysMessageEntity);
				}else{
					count = messagesDao.getAllRowCount();
				}
			}
			map.put("total",count);
			map.put("dataList",res);
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	/**
	 * 前往消息列表
	 * @param sysMessageEntity
     * @return
     */
	@Override
	public ModelAndView redirect(SysMessageEntity sysMessageEntity) {
		try{
			if(sysMessageEntity.getId()==null){
				sysMessageEntity = new SysMessageEntity();
			}else{
				sysMessageEntity = this.getEntity(SysMessageEntity.class, sysMessageEntity.getId());
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return new ModelAndView("messages/createMessages.html","messages", sysMessageEntity);
	}

	/**
	 * 新增或者修改消息
	 * @param sysMessageEntity
	 * @param session
     * @return
     */
	@Override
	public AjaxJson save(SysMessageEntity sysMessageEntity, HttpSession session) {
		AjaxJson ajaxJson = new AjaxJson();
		String nowTime = StringUtil.getNowTime();
		String userid = (String) session.getAttribute("userId");
		TbSysUsers tbSysUsers = userDao.get(userid);
		String id = tbSysUsers.getPkUserId();
		String name = tbSysUsers.getUserName();
		try{
			if(StringUtil.isNotEmpty(sysMessageEntity.getId())){
				sysMessageEntity.setUpdateTime(nowTime);
				sysMessageEntity.setUpdateUser(id);
				attachmentService.delSomeData(sysMessageEntity.getId());
				attachmentService.updateMeAttach(sysMessageEntity,nowTime,id);
				messagesUsersService.delSomeData(sysMessageEntity.getId());
				messagesUsersService.updateMess(sysMessageEntity,nowTime,id);
				this.update(sysMessageEntity);
			}else{
				sysMessageEntity.setCreateTime(nowTime);
				sysMessageEntity.setUpdateTime(nowTime);
				sysMessageEntity.setCreateUser(id);
				sysMessageEntity.setUpdateUser(id);
				sysMessageEntity.setPublish(name);
				sysMessageEntity.setStatus(0);
				sysMessageEntity.setReadTime("");
				this.save(sysMessageEntity);
				attachmentService.saveMeAttach(sysMessageEntity,nowTime,id);
				messagesUsersService.saveMess(sysMessageEntity,nowTime,id);
//				Sender.Send(sysMessageEntity);
//				session.setAttribute("writer",1);
			}
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}

		return ajaxJson;
	}

	/**
	 * 修改
	 * @param sysMessageEntity
	 * @param session
     * @return
     */
	@Override
	public AjaxJson update(SysMessageEntity sysMessageEntity, HttpSession session) {
		AjaxJson ajaxJson = new AjaxJson();
		try{
			String userid = (String) session.getAttribute("userId");
			TbSysUsers tbSysUsers = userDao.get(userid);
			String id = tbSysUsers.getPkUserId();
			String nowTime = StringUtil.getNowTime();
			sysMessageEntity.setUpdateTime(nowTime);
			sysMessageEntity.setUpdateUser(id);
			this.update(sysMessageEntity);
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	/**
	 * 消息删除
	 * @param sysMessageEntity
     * @return
     */
	@Override
	public AjaxJson deletes(SysMessageEntity sysMessageEntity) {
		AjaxJson ajaxJson = new AjaxJson();
		try{
			attachmentService.delSomeData(sysMessageEntity.getId());
			messagesUsersService.delSomeData(sysMessageEntity.getId());
			this.delete(sysMessageEntity);
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	/**
	 * 批量删除
	 * @param ids
     * @return
     */
	@Override
	public AjaxJson deleteSome(String[] ids) {
		AjaxJson ajaxJson = new AjaxJson();
		try{
			for(int i=0;i<ids.length;i++){
				SysMessageEntity res = this.getEntity(SysMessageEntity.class,ids[i]);
				attachmentService.delSomeData(ids[i]);
				messagesUsersService.delSomeData(ids[i]);
				this.delete(res);
			}
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	/**
	 * 修改消息状态
	 * @param id
     * @return
     */
	@Override
	public AjaxJson updateStatus(String id) {
		AjaxJson ajaxJson = new AjaxJson();
		try{
			this.updateBySqlString(id);
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		return ajaxJson;
	}

	@Override
	public AjaxJson myList(SysMessageEntity sysMessageEntity, Integer pagenum, Integer pagesize,String userID) {
		SysMessageUserEntity user = new SysMessageUserEntity();
		user.setMessagesUserid(userID);
		List<SysMessageUserEntity> userList = messagesUsersService.queryList(user);
		SysMessageUserEntity newUser = userList.get(0);
		String userName = newUser.getId();
		HashMap<String, Object> map = new HashMap<>();
		AjaxJson ajaxJson = new AjaxJson();
		try {
			sysMessageEntity.setReceiveObject(userID);
			List<SysMessageEntity> res = messagesDao.myPage(sysMessageEntity,pagenum,pagesize);
			Integer count=0;
			if(StringUtil.isNotEmpty(sysMessageEntity.getTitle())||StringUtil.isNotEmpty(sysMessageEntity.getType())||StringUtil.isNotEmpty(sysMessageEntity.getStatus())){
				count = messagesDao.getCountBy(sysMessageEntity);
			}else{
				count = messagesDao.getAllRowCount();
			}
			map.put("dataList",res);
			map.put("total",count);
		}catch (Exception e){
			ajaxJson.setCode(201);
			ajaxJson.setMsg("error");
			e.printStackTrace();
		}
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	@Override
	public ModelAndView updateReadMessage(SysMessageEntity sysMessageEntity,String userID) {
		try{
			String roleName = getRoleName(userID);
			String nowtime = StringUtil.getNowTime();
			sysMessageEntity = this.getEntity(SysMessageEntity.class, sysMessageEntity.getId());
			TbSysUsers user = userDao.get(userID);
			if(sysMessageEntity.getPublish().equals(user.getUserName())){
				//不改状态
			}else if(roleName.indexOf("admin")!=-1&& sysMessageEntity.getReceiveObject().indexOf(user.getPkUserId())!=-1){
//				sysMessageEntity.setStatus(1);
				sysMessageEntity.setReadTime(nowtime);
			}else if(roleName.indexOf("admin")!=-1){
				//不改状态
			}else{
//				sysMessageEntity.setStatus(1);
				sysMessageEntity.setReadTime(nowtime);
			}


			this.update(sysMessageEntity);

		}catch (Exception e){
			e.printStackTrace();
		}
		return new ModelAndView("messages/message.html","messages", sysMessageEntity);
	}

	@Override
	public ModelAndView editReadMessage(String messageid) {
		SysMessageEntity sysMessageEntity=null;
		try{
			String nowtime = StringUtil.getNowTime();
			sysMessageEntity = this.getEntity(SysMessageEntity.class, messageid);
			sysMessageEntity.setReadTime(nowtime);
			this.update(sysMessageEntity);
		}catch (Exception e){
			e.printStackTrace();
		}
		return new ModelAndView("messages/message.html","messages", sysMessageEntity);
	}

	private String getRoleName(String userID){
		List<TbSysRoleUser> roleUsers = roleUserDao.getRoleUserByUserId(userID);
		String roleName = "";
		for (int i = 0; i < roleUsers.size(); i++) {
			TbSysRoleUser roleUser = roleUsers.get(i);
			TbSysRoles role = new TbSysRoles();
			role.setPkRoleId(roleUser.getRoleId());
			TbSysRoles newRole = roleDao.selectOne(role);
			roleName+=newRole.getRoleName()+",";
		}
		return roleName;
	}

	@Override
	public AjaxJson getMessageNum(String userID) {
		AjaxJson ajaxJson = new AjaxJson();
		HashMap<String, Object> map = new HashMap<>();
		Integer num = messagesDao.getMessageNum(userID);
		map.put("num",num);
		ajaxJson.setResult(map);
		return ajaxJson;
	}

	@Override
	public AjaxJson getMessage(String userID) {
		AjaxJson ajaxJson = new AjaxJson();
		HashMap<String, Object> map = new HashMap<>();
		List<SysMessageEntity> sysMessageEntityList =messagesDao.getsysmess(userID);
		int size = sysMessageEntityList.size();
		map.put("num",size);
		map.put("messageBean",sysMessageEntityList);
		ajaxJson.setResult(map);
		return ajaxJson;
	}
}
